//
//  ZClubsListVC.m
//  WeClubs
//
//  Created by 花花 on 2017/6/21.
//  Copyright © 2017年 Zed. All rights reserved.
//

#import "ZClubsListVC.h"
#import "ZClubsListHeaderView.h"
#import "ZMemberGroupModel.h"
#import "ZCommentHeader.h"
#import "ZClubMemberCell.h"
#import "ZNewNotifyVC.h"
#import "ZNewMissionVC.h"
@interface ZClubsListVC ()<UITableViewDelegate,UITableViewDataSource>
//tableView
@property(nonatomic)UITableView *tableView;

//[@"姓名",@"部门",@"年级",@"职位"];
@property(nonatomic)ZClubsListHeaderView *headerView;

//搜索
@property(nonatomic)UISearchBar *searchBar;

//数据源
@property(nonatomic)NSMutableArray *memberDataArr;

//右边索引
@property(nonatomic)NSMutableArray *indexDataArr;

@property(nonatomic)NSMutableArray *temp;
//点击右边索引提示
@property(nonatomic,weak)UILabel *alertLabel;

@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,strong)UIButton *selBtn;
@end
NSString * const MemberManagerHeaderReuse = @"ZMemberManagerHeaderReuse";
NSString * const ClubMemberCellReuse = @"ZClubMemberCellReuse";

@implementation ZClubsListVC

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];

    [self loadDataFormNetWork:ZSortType_Initial]; //默认按姓名排序
}

#pragma mark - setupNav
- (void)zConfigNavigation{
    [super zConfigNavigation];
    
    [self zAddBackItemWithGesture:YES];

    UIBarButtonItem *btn1 = [self zNavItemWithTitle:@"全选" andSelector:@selector(navAllSelectOnClick:)];
    UIBarButtonItem *btn2 = [self zNavItemWithTitle:@"确定" andSelector:@selector(determineOnClick)];
    self.navigationItem.rightBarButtonItems  = @[btn2,btn1];
    
}
#pragma mark - init Methods
-(void)initUI{
    
     [self.view addSubview:self.tableView];
    
     [self.view addSubview:self.searchBar];
    
     [self.view addSubview:self.headerView];
 
}
#pragma mark - loadData
- (void)loadDataFormNetWork:(ZSortType)type{

    [MBProgressHUD zAlertProgress:@"正在加载中"];
    [self.memberDataArr removeAllObjects];
    [self.indexDataArr removeAllObjects];

    NSDictionary *params = @{
                             @"club_id":@(self.club_id),
                             @"sort_type":@(type),
                             };
    [HTTPRequest POST:kGet_club_studentsUrl parameter:params success:^(id resposeObject) {
               [MBProgressHUD zAlertHideHUD];
        
        if ([resposeObject[@"result_code"] integerValue] == ZNetManagerStatusSuccess) {
        for (NSDictionary *dict in resposeObject[@"data"][@"groups"]) {
            
            ZMemberGroupModel * model = [[ZMemberGroupModel alloc]initWithDictionary:dict];
            
            model.group_name = dict[@"group_name"];
            [self.indexDataArr addObject:model.group_name];
            [self.memberDataArr addObject:model];

        }
            [self.tableView reloadData];
        }else{
            
           [MBProgressHUD zAlertMessage:resposeObject[@"result_msg"] to:self.view afterDelay:1.0];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD zAlertHideHUD];
    }];

}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.memberDataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    ZMemberGroupModel * model = self.memberDataArr[section];
    return model.studentsArr.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZClubMemberCell *cell = [tableView dequeueReusableCellWithIdentifier:ClubMemberCellReuse];
    cell.messageBtn.hidden = NO;
    [cell.messageBtn setImage:[UIImage imageNamed:@"sign_ic_uncertain"] forState:UIControlStateNormal];
    [cell.messageBtn setImage:[UIImage imageNamed:@"sign_ic_sure"] forState:UIControlStateSelected];
    cell.productSelectedCallBack = ^(ZClubMemberCell *cell,BOOL isSelected){

        [self productSelected:cell isSelected:isSelected];
    };
    ZMemberGroupModel *model = self.memberDataArr[indexPath.section];
    ZStudentModel *studentModel = model.studentsArr[indexPath.row];
    cell.messageBtn.selected = studentModel.isChoosed;
    cell.model = studentModel;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   ZClubSectionHeaderView *headerView = [[ZClubSectionHeaderView alloc]init];
    ZMemberGroupModel *model = self.memberDataArr[section];
    headerView.allBtn.hidden = NO;
    headerView.allBtn.selected = model.isChoosed;
    headerView.allBtn.selected = model.isEditing;
    headerView.titleLabel.text =model.group_name;
    headerView.callback = ^{
        [self headerAllSelected:section];
    };

    return headerView;
}

//- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
//
//    return self.indexDataArr;
//
//}
//
//-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
//
//    ZLog(@"===%@  ===%zd",title,index);
//    [self showSelectedTitle:title];
//    return index;
//}
#pragma mark - Custom Methods
-(void)showSelectedTitle:(NSString*)title{
    
    [self.alertLabel setText:title];
    self.alertLabel.hidden = NO;
    self.alertLabel.alpha = 1.0;
    [self.timer invalidate];
    self.timer = nil;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAnimation:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)timerAnimation:(NSTimer *)timer{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.25 animations:^{
            self.alertLabel.alpha = 0;
        } completion:^(BOOL finished) {
            self.alertLabel.hidden = YES;
        }];
    });
}

//组头全选
- (void)headerAllSelected:(NSInteger)sectionIndex{
    
    ZMemberGroupModel *buyer = self.memberDataArr[sectionIndex];
    buyer.isChoosed = !buyer.isChoosed;
    [buyer.studentsArr enumerateObjectsUsingBlock:^(ZStudentModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isChoosed = buyer.isChoosed;
    }];
    [self.tableView reloadData];
}
//cell的选中
-(void)productSelected:(ZClubMemberCell *)cell isSelected:(BOOL)choosed{
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ZMemberGroupModel *groupModel  = self.memberDataArr[indexPath.section];
    ZStudentModel *studentModel = groupModel.studentsArr[indexPath.row];
    studentModel.isChoosed = !studentModel.isChoosed;
    // 当点击单个的时候，判断是否该组下面的成员是否全部选中
    __block NSInteger count = 0;
    [groupModel.studentsArr enumerateObjectsUsingBlock:^(ZStudentModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isChoosed) {
            count ++;
        }
    }];
    if (count ==groupModel.studentsArr.count) {
        groupModel.isChoosed = YES;
    }else{
        groupModel.isChoosed = NO;
    }
    [self.tableView reloadData];
    
}
#pragma mark - SEL Methods
//nav全选 ->列表全部选中
- (void)navAllSelectOnClick:(UIButton*)btn{

    
    btn.selected = !btn.selected;
    for (ZMemberGroupModel *groupModel in self.memberDataArr) {
        groupModel.isChoosed = btn.selected;
        for (ZStudentModel *studentModel in groupModel.studentsArr) {
            studentModel.isChoosed = groupModel.isChoosed;
        }
    }
    [self.tableView reloadData];
}

// 确定

-(void)determineOnClick{
    
    ZLog(@"888888888888--------%zd",[self countTotalSelectedNumber]);
  
    for (ZNewNotifyVC *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[ZNewNotifyVC class]]) {
            
            temp.club_name = self.title;
            temp.dataArr = _temp;
            temp.club_id = self.club_id;
            [self.navigationController popToViewController:temp animated:YES];
                
     }
   }
    for (ZNewMissionVC *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[ZNewMissionVC class]]) {            
            temp.club_name = self.title;
            temp.dataArr = _temp;
            temp.club_id = self.club_id;
            [self.navigationController popToViewController:temp animated:YES];
            
        }
    }
    
    
    
    
}
//选中的人数
- (NSInteger)countTotalSelectedNumber{

     _temp = [NSMutableArray array];
    NSInteger count= 0;
    
    for (ZMemberGroupModel *grouoModel in self.memberDataArr) {
        
        for (ZStudentModel *studentModel in grouoModel.studentsArr) {
            
            if (studentModel.isChoosed) {
                
                [_temp addObject:studentModel];
                count ++;
            }
        }
    }

    return count;
}

#pragma mark - Setter && Getter Methods
- (UISearchBar *)searchBar{
    
    if (!_searchBar) {
        _searchBar= [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, Z_SCREEN_WIDTH, 44)];
        [_searchBar setPlaceholder:@"搜索社团成员"];
        [_searchBar setBackgroundColor:GENERAL_VIEW_BG_COLOR];
        [_searchBar setSearchBarStyle:UISearchBarStyleMinimal];
        [_searchBar setSearchFieldBackgroundImage:[UIImage zImageWithColor:NAVBAR_BG_COLOR size:CGSizeMake(self.view.width, 28) andRadius:4] forState:UIControlStateNormal];
    }
    return _searchBar;
}
- (ZClubsListHeaderView *)headerView{
    
    if (!_headerView) {
        _headerView = [[ZClubsListHeaderView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), Z_SCREEN_WIDTH, 40)];
        Z_WEAK_SELF;
        _headerView.handlerBtnClickCallBack = ^(UIButton *btn){
            btn.selected =! btn.selected;
            
            [weakSelf loadDataFormNetWork:btn.tag];
        };
    }
    return _headerView;
}

-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40+64+45, Z_SCREEN_WIDTH, Z_SCREEN_HEIGHT -(40+64+45)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setBackgroundColor:GENERAL_VIEW_BG_COLOR];
        _tableView.separatorColor = GENERAL_VIEW_BG_COLOR;
        _tableView.estimatedRowHeight = 88;
        [_tableView registerNib:[UINib nibWithNibName:@"ZClubMemberCell" bundle:nil] forCellReuseIdentifier:ClubMemberCellReuse];
    }
    return _tableView;
}
//设置提示的Label
-(UILabel *)alertLabel{
    
    if (!_alertLabel) {
        
        UILabel *alertLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 88, 88)];
        alertLabel.center = self.view.center;
        alertLabel.textAlignment = NSTextAlignmentCenter;
        alertLabel.textColor = HIGHTLIGHT_COLOR;
        alertLabel.font =[UIFont systemFontOfSize:15];
        alertLabel.backgroundColor =[UIColor whiteColor];
        alertLabel.layer.cornerRadius = 10;
        alertLabel.layer.masksToBounds =YES;
        alertLabel.layer.borderWidth = 5.0f;
        alertLabel.layer.borderColor =[UIColor grayColor].CGColor;
        [self.navigationController.view addSubview:alertLabel];
        _alertLabel = alertLabel;
        self.alertLabel.hidden = YES;
    }
    return _alertLabel;
}

- (NSMutableArray *)memberDataArr{

    if(!_memberDataArr){
        _memberDataArr = [NSMutableArray array];
    }
    return _memberDataArr;
}
- (NSMutableArray *)indexDataArr{

    if (!_indexDataArr) {
        _indexDataArr =[NSMutableArray array];
    }
    return _indexDataArr;
}
@end
